<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class AuthController extends Controller
{
    /**
     * 微信小程序登录
     */
    public function wxLogin(Request $request)
    {
        $code = $request->input('code');
        $userInfo = $request->input('userInfo');
        
        if (!$code) {
            return response()->json([
                'code' => 400,
                'message' => '缺少code参数'
            ]);
        }
        
        // 这里需要配置微信小程序的appid和secret
        $appid = env('WECHAT_MINI_PROGRAM_APPID');
        $secret = env('WECHAT_MINI_PROGRAM_SECRET');
        
        // 调用微信接口获取openid
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code";
        
        $response = file_get_contents($url);
        $data = json_decode($response, true);
        
        if (isset($data['errcode'])) {
            return response()->json([
                'code' => 400,
                'message' => '微信登录失败：' . $data['errmsg']
            ]);
        }
        
        $openid = $data['openid'];
        $sessionKey = $data['session_key'];
        
        // 生成自定义token（这里简化处理，实际项目建议使用JWT）
        $token = md5($openid . time());
        
        return response()->json([
            'code' => 200,
            'message' => '登录成功',
            'data' => [
                'token' => $token,
                'openid' => $openid,
                'userInfo' => $userInfo
            ]
        ]);
    }
}
